﻿using AutoMapper;
using Microsoft.AspNetCore.SignalR;
using Warehouse.IServices.Conveyorlines;
using WCS.IServices;
using WCS.Services;
using WCS.ViewModels;

namespace WCS.LongTaskService
{

    /// <summary>
    /// 创建任务监控类
    /// </summary>
    public class TaskCreateService : BackgroundService
    {
        private readonly ILogger<TaskCreateService> logger;
        private readonly IDeviceManager deviceManager;
        private readonly IHubContext<ReportHub> _hubContext;
        private readonly IMapper mapper;
        private readonly IConveyorIServices conveyorIServices;

		public TaskCreateService(ILogger<TaskCreateService> logger,
            IDeviceManager deviceManager,
            IHubContext<ReportHub> hubContext,
            IMapper mapper,
            IConveyorIServices conveyorIServices)
        {
            this.logger = logger;
            this.deviceManager = deviceManager;
            _hubContext = hubContext;
            this.mapper = mapper;
            this.conveyorIServices = conveyorIServices;
        }


        /// <summary>
        /// 监控主方法
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
                while (!stoppingToken.IsCancellationRequested)
                {
                    try
                    {
                        deviceManager.DeviceMonitor();
                        conveyorIServices.CheckConveyor();
                        var dtos = mapper.Map<List<PortShowDto>>(deviceManager.Ports);
                        await _hubContext.Clients.All.SendAsync("DeviceInfo", mapper.Map<List<PortShowDto>>(deviceManager.Ports));

                        await Task.Delay(TimeSpan.FromSeconds(3));
                    }
                    catch (Exception ex)
                    {

                        logger.LogError($"Create job occur cancel error.Error msg is:{ex.Message},stacker is:{ex.StackTrace}");
                    }
                  
                }
          
           

        }
    }
}
